package com.lw.lost.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.MessageAdapter
import com.lw.lost.databinding.ActivityChatBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.Message
import com.lw.lost.utils.FileUtils
import com.lw.lost.utils.PreferenceUtils

class ChatActivity : AppCompatActivity() {

    private lateinit var binding: ActivityChatBinding
    private lateinit var db: DBlost
    private lateinit var messageAdapter: MessageAdapter
    private var targetUserId: Long = -1
    private var currentUserId: Long = -1
    private var selectedImageUri: Uri? = null

    private val getContent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                selectedImageUri = uri
                // 发送图片消息
                sendImageMessage(uri)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChatBinding.inflate(layoutInflater)
        setContentView(binding.root)

        targetUserId = intent.getLongExtra("userId", -1)
        if (targetUserId == -1L) {
            finish()
            return
        }

        db = DBlost(this)
        currentUserId = PreferenceUtils.getUserId(this)

        // 设置标题
        val cursor = db.userDao.getUserById(targetUserId)
        cursor.use { cursor ->
            if (cursor.moveToFirst()) {
                val name = cursor.getString(cursor.getColumnIndexOrThrow("name"))
                setSupportActionBar(binding.toolbar)
                supportActionBar?.setDisplayHomeAsUpEnabled(true)
                supportActionBar?.title = name
            }
        }

        setupRecyclerView()
        setupSendButton()
        setupImageButton()
        loadMessages()

        // 标记消息为已读
        db.messageDao.markAsRead(targetUserId, currentUserId)
    }

    private fun setupRecyclerView() {
        messageAdapter = MessageAdapter(currentUserId)
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context).apply {
                stackFromEnd = true  // 从底部开始显示
            }
            adapter = messageAdapter
        }
    }

    private fun setupSendButton() {
        binding.btnSend.setOnClickListener {
            val content = binding.etMessage.text.toString().trim()
            if (content.isEmpty()) {
                return@setOnClickListener
            }

            // 发送消息
            val result = db.messageDao.insert(currentUserId, targetUserId, content)
            if (result > 0) {
                binding.etMessage.text?.clear()
                loadMessages()  // 重新加载消息列表
                binding.recyclerView.smoothScrollToPosition(messageAdapter.itemCount)
            } else {
                Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun setupImageButton() {
        binding.btnImage.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                // Android 13及以上
                if (checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(arrayOf(Manifest.permission.READ_MEDIA_IMAGES), 100)
                } else {
                    openImagePicker()
                }
            } else {
                // Android 13以下
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 100)
                } else {
                    openImagePicker()
                }
            }
        }
    }

    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        getContent.launch(intent)
    }

    private fun sendImageMessage(imageUri: Uri) {
        // 保存图片到应用私有目录
        FileUtils.saveImageToPrivateStorage(this, imageUri)?.let { file ->
            // 发送消息
            val result = db.messageDao.insert(
                senderId = currentUserId,
                receiverId = targetUserId,
                content = "[图片]",
                imageUrl = file.absolutePath
            )
            
            if (result > 0) {
                loadMessages()
                binding.recyclerView.smoothScrollToPosition(messageAdapter.itemCount)
            } else {
                Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadMessages() {
        val messages = mutableListOf<Message>()
        db.messageDao.getMessageHistory(PreferenceUtils.getUserId(this), targetUserId).use { cursor ->
            while (cursor.moveToNext()) {
                messages.add(
                    Message(
                        messageId = cursor.getLong(cursor.getColumnIndexOrThrow("messageId")),
                        senderId = cursor.getLong(cursor.getColumnIndexOrThrow("senderId")),
                        content = cursor.getString(cursor.getColumnIndexOrThrow("content")),
                        imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("imageUrl")),
                        sendTime = cursor.getString(cursor.getColumnIndexOrThrow("sendTime")),
                        senderAvatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
                    )
                )
            }
        }
        messageAdapter.submitList(messages)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openImagePicker()
            } else {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show()
            }
        }
    }
} 